package cn.mvc.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.nio.file.Files;

/**
 * @author yexi
 */
@Controller
public class UploadController {
    // Spring 容器存在 ServletContext 类型的对象，所以定义好 ServletContext 类型字段贴@Autowired注解即可获取到
    @Autowired
    private ServletContext servletContext;

    @RequestMapping("/upload")
    public ModelAndView upload(Part pic) throws Exception {
        System.out.println(pic.getContentType()); // 文件类型
        System.out.println(pic.getName()); // 文件参数名
        System.out.println(pic.getSize()); // 文件大小
        System.out.println(pic.getInputStream()); // 文件输入流
        // FileCopyUtils.copy(in, out)，一个 Spring 提供的拷贝方法
        // 获取项目 webapp 目录下 uploadDir 目录的绝对路径
        System.out.println(servletContext.getRealPath("/uploadDir"));
        return null;
    }

    @RequestMapping("/video")
    public void video(HttpServletResponse response) throws Exception {
        File file = new File("E:\\WeChat Files\\wxid_uabij05tni3822\\FileStorage\\Video\\2023-06\\a53d9ae47586e282771efe585b11c144.mp4");
        byte[] bytes = Files.readAllBytes(file.toPath());
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
    }

}
